//
//  Yahoo_Web_History.m
//  MacStockApp
//
//  Created by 英傑 翁 on 12/3/28.
//  Copyright (c) 2012年 翁英傑. All rights reserved.
//
#import "XX_XQData_History.h"
#import "Yahoo_Web_History.h"
#import "GBTableColumnHeader.h"
#import "GBTableColumnHeader_basicSqlite.h"
#import "GBTableColumnHeader_quote.h"
#import "GBTableColumnHeader_2Row3Row.h"
#import "GBTableColumnHeader_node.h" 
#import "GBTableColumnHeader_position.h"  
#import "GBTableColumnHeader_position_bottom_sumaverage.h"  
#import "GBTableColumnHeader_Indicator.h"  
#import "GBTableColumnHeader_signal.h"  
#import "GBTableColumnHeader_ObjectOtherKey.h"  
#import "GBall.h"

@implementation Yahoo_Web_History


@synthesize delgeate;

-(id)init_With_Code:(NSString *)codea file_code:(NSString *)file_code table_quote_date:(NSDate *)dateq timezone:(NSString *)tz is_have_to_reload_data:(BOOL)have_to_reload{
	
    if(self=[super init])
	{
        
       
        have_to_reload_data=have_to_reload;        
        code=codea;
        
        read_write_file_code=file_code;
        table_quote_date=dateq;
        timezone=tz;
        
        [code retain];
        [read_write_file_code retain];
        [table_quote_date retain];
        [timezone retain];        
        
        
    }
	
	return self;
}

-(void)dealloc{
    if (code) {
        [code release]; 
    }
    if (read_write_file_code) {
        [read_write_file_code release];
    }
    if (table_quote_date) {
        [table_quote_date release];
    }
    if (timezone) {
        [timezone release];
    }
    
    [super dealloc];
}

- (void)main 
{ 
    
    if (have_to_reload_data) {
       
        NSMutableDictionary *all_history_data;
       
        //如果有xq資料
        if ([XX_XQData_History isHaveXQ_Dairly_Data:read_write_file_code]) {
            
            all_history_data=[XX_XQData_History read_XQ_Dairly_Data:read_write_file_code _code:code _timezone:timezone];
            
        }
        else{
            //一次全部下載的年限
            int download_year;
            download_year=10;
            
            //歷史資料 含時間序列 與最後一筆的時間與收盤價 及此段時間內最大值與最低值
            
            
            //歷史檔案路徑
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
            NSString *Path_HistoryData  ;
            Path_HistoryData=[prefs objectForKey:Defaults_Path_HistoryData];
            
            NSString *filename;
            filename=[NSString stringWithFormat: @"%@.plist",read_write_file_code];
            NSString * write_FilepathnName= [Path_HistoryData stringByAppendingPathComponent:filename]  ;
            
            
            //1.歷史資料檔案處理
            {
                
                NSFileManager *fileManager = [NSFileManager defaultManager];
                BOOL success = [fileManager fileExistsAtPath:write_FilepathnName];
                //有歷史檔案
                if (success ) {
                    
                    //從檔案上取出資料
                    all_history_data= [NSMutableDictionary dictionaryWithContentsOfFile:  write_FilepathnName] ;
                    
                    //取出檔案上 最後日期
                    NSDate *file_history_lastdate=[all_history_data objectForKey:@"last_his_date"]  ;
                    //取出檔案上 最後調整後收盤價
                    NSNumber *file_history_last_adjclose=[all_history_data objectForKey:@"last_his_close"] ;
                    //取出檔案上 最高價與最低價
                    NSNumber *file_his_high=[all_history_data objectForKey:@"his_data_high"] ;
                    NSNumber *file_his_low=[all_history_data objectForKey:@"his_data_low"] ;
                    
                    //下載部分資料
                    {
                        //部分資料的開始日與結束日
                        NSDate *start_date;
                        NSDate *end_date;
                        start_date=file_history_lastdate; //開始日是以檔案上最後一筆時間開始
                        end_date=[NSDate date];//結束日就是現在
                        
                        //如果結束日與開始日相差至少2天以上才要進行回補部分歷史資料
                        if ([self convert_NSDate_to_int:end_date]-[self convert_NSDate_to_int:start_date]>1) {
                            
                            //取出部分歷史資料
                            NSMutableDictionary *partial_history_data;
                            partial_history_data= [self Get_hisstory_data_startdate:start_date end_date:end_date] ;
                            
                            //成功取出部分歷史資料
                            if (partial_history_data!=nil  ) {
                                //部分歷史資料的時間序列
                                NSArray *partial_history_array;
                                partial_history_array=[partial_history_data objectForKey:@"his_data"];
                                
                                //時間序列數量至少要大於1
                                if ([partial_history_array count ]>=1) {
                                    
                                    //檢查檔案最後一筆資料的調整收盤價是否與新出來的調整收盤價是否相同
                                    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
                                    //[numberFormatter setFormat:@"###,###,##0.###"];
                                    
                                    NSString *file_adjclose;
                                    NSString *web_adjclose;
                                    file_adjclose=[numberFormatter stringFromNumber:file_history_last_adjclose];
                                    //部分歷史資料序列的第一筆資料的調整收盤價
                                    web_adjclose=[numberFormatter stringFromNumber:[[partial_history_array objectAtIndex:0] objectForKey:HIS_basic_adjclose]];
                                    [numberFormatter release];
                                    
                                    NSLog(@"比較收盤價 %@ %@",file_adjclose,web_adjclose);
                                    
                                    //調整收盤價相同=>添加進去
                                    if ([file_adjclose isEqualToString:web_adjclose]  ) {
                                        NSLog(@"調整收盤價相同=>添加進去");
                                        
                                        //為何下載的部分歷史資料序列要大於或等於2=>因為第一筆其實就是等於原本檔案上的最後一筆
                                        if ([partial_history_array count]>=2) {
                                            //注意i =1 開始加入
                                            for (int i=1; i<[partial_history_array count]; i++) {
                                                
                                                //實際添加歷史資料
                                                [[all_history_data objectForKey:@"his_data"] addObject:[partial_history_array objectAtIndex:i]];
                                                //添加其他附屬資料 最後日期 最後價格 與最高與最低
                                                {
                                                    [all_history_data setObject:[partial_history_data objectForKey:@"last_his_date"] forKey:@"last_his_date"];
                                                    
                                                    [all_history_data setObject:[partial_history_data objectForKey:@"last_his_close"] forKey:@"last_his_close"];
                                                    
                                                    //全部資料最高與最低
                                                    {
                                                        if ([[partial_history_data objectForKey:@"his_data_high"] doubleValue] >[file_his_high doubleValue]) {
                                                            
                                                            [all_history_data setObject:[partial_history_data objectForKey:@"his_data_high"] forKey:@"his_data_high"];
                                                            file_his_high=[partial_history_data objectForKey:@"his_data_high"] ;
                                                        }
                                                        if ([[partial_history_data objectForKey:@"his_data_low"] doubleValue] <[file_his_low doubleValue]) {
                                                            
                                                            [all_history_data setObject:[partial_history_data objectForKey:@"his_data_low"] forKey:@"his_data_low"];
                                                            
                                                            file_his_low=[partial_history_data objectForKey:@"his_data_low"] ;
                                                        }
                                                    }
                                                    
                                                    
                                                    
                                                }
                                                
                                                
                                            }
                                            //儲存資料
                                            [all_history_data writeToFile:write_FilepathnName atomically:YES];
                                            
                                        }
                                        
                                        
                                    }
                                    //調整收盤價不相同=>全部重讀
                                    else {
                                        NSLog(@"調整收盤價不相同=>全部重讀");
                                        //下載歷史全部資料
                                        {
                                            NSDate *start_date;
                                            NSDate *end_date;
                                            NSTimeInterval ti;
                                            ti=-1*60*60*24*365*download_year;//  往前推10年資料下載
                                            start_date=[NSDate dateWithTimeInterval:ti sinceDate: [NSDate date]];
                                            end_date=[NSDate date];
                                            
                                            all_history_data=[self Get_hisstory_data_startdate:start_date end_date:end_date];
                                            
                                            //儲存資料
                                            [all_history_data writeToFile:write_FilepathnName atomically:YES];
                                        }
                                        
                                    }
                                }
                                
                            }
                        }
                        
                    }
                    
                    
                    
                    //檢查代碼是否相同
                    if (![[all_history_data objectForKey:DB_object_sqlite_basic_code] isEqualToString:code  ]) {
                        
                        NSLog(@"yahoo web檔案上的返回識別碼 a=%@", [all_history_data objectForKey:DB_object_sqlite_basic_code]);
                        NSLog(@"yahoo web報價的識別碼 b=%@", code);
                        
                        
                        [all_history_data removeObjectForKey:DB_object_sqlite_basic_code];
                        [all_history_data setObject:code forKey:  DB_object_sqlite_basic_code ];
                        [all_history_data writeToFile:write_FilepathnName atomically:YES];
                    }
                    
                    
                    
                    
                }
                //無歷史檔案
                else {
                    NSLog(@"無檔案");
                    
                    //下載歷史全部資料
                    {
                        NSDate *start_date;
                        NSDate *end_date;
                        NSTimeInterval ti;
                        ti=-1*60*60*24*365*download_year;//  往前推10年資料下載
                        start_date=[NSDate dateWithTimeInterval:ti sinceDate: [NSDate date]];
                        end_date=[NSDate date];
                        
                        all_history_data=[self Get_hisstory_data_startdate:start_date end_date:end_date];
                        
                        //儲存資料
                        if (all_history_data!=nil) {
                            [all_history_data writeToFile:write_FilepathnName atomically:YES];
                        }
                        
                    }
                    
                }
            }
            
            
            //2.比較最後一筆歷史資料與報價表時間上差異再來決定是否要利用最近五日tick資料來補缺額的時間
            {
                
                //已經取得的歷史資列序列最後一筆日期 理論上是網路上最完整可以取得的資料
                NSDate *history_lastdate;
                history_lastdate=  [all_history_data objectForKey:@"last_his_date"]  ;
                
                int int_history_lastdate;
                int int_table_quote_date;
                int_history_lastdate=[self convert_NSDate_to_int:history_lastdate];
                int_table_quote_date=[self convert_NSDate_to_int:table_quote_date];
                
                
                //NSLog(@"歷史資料表上最後日期=%i code=%@",  int_history_lastdate,code  );
                //NSLog(@"報價表上最新日期=%i code=%@",  int_table_quote_date ,code );
                
                //需要回補缺額資料=>表示網路上的歷史資料有缺
                
                int day=60*60*24*1;
                int diff=abs([table_quote_date timeIntervalSince1970]-[history_lastdate timeIntervalSince1970] )/day ;
                
                NSLog(@"差距=%i",diff);
                
                if (diff>=2) {
                    
                    NSLog(@"需要回補缺額資料=>表示網路上的歷史資料有缺");
                    
                    //取出最近五日資料
                    NSMutableArray *ARRAY_5D;
                    ARRAY_5D=[self Get_5d_hisstory_data];
                    
                    if (ARRAY_5D) {
                        //將分時資料轉成的五日時間序列資料全部取出
                        for (NSMutableDictionary *rrd in ARRAY_5D ) {
                            
                            int get_5day_date;
                            get_5day_date=[self convert_NSDate_to_int:[rrd objectForKey:HIS_basic_date]];
                            
                            //比較只需要在歷史最後ㄧ日與報價日中間的需要加入
                            if (int_history_lastdate<get_5day_date && get_5day_date< int_table_quote_date) {
                                NSLog(@"比較只需要在歷史最後ㄧ日與報價日中間的需要加入=%@ %@ %@ %@ %@ %@",[rrd objectForKey:HIS_basic_date],[rrd objectForKey:HIS_basic_open],[rrd objectForKey:HIS_basic_close],[rrd objectForKey:HIS_basic_high],[rrd objectForKey:HIS_basic_low],[rrd objectForKey:HIS_basic_vol] );                    
                                
                                [[all_history_data objectForKey:@"his_data"] addObject:rrd ];                
                            }
                            
                        }
                        
                        
                    }        
                    
                    
                    
                    
                }
                //不需要回補缺額 =>表示網路上的歷史資料完整    
                else {
                    //不需要回補缺額
                    NSLog(@"不需要回補缺額 =>表示網路上的歷史資料完整 " );
                }
                
            }
        }         
       
        //3.將整理好的開收高低成交量資料傳出來
        NSLog(@"將整理好的開收高低成交量資料傳出來=%@",code);
        
        [(Data_Model *)delgeate performSelectorOnMainThread:@selector(His_Data_Finished:) withObject:all_history_data waitUntilDone:YES];
    }
    else {
        
        NSMutableDictionary *out_dic=[[[NSMutableDictionary alloc] init] autorelease];
        [out_dic setObject:code forKey:DB_object_sqlite_basic_code];        
        [(Data_Model *)delgeate performSelectorOnMainThread:@selector(His_Data_Finished_not_reload:) withObject:out_dic waitUntilDone:YES];    
    }    
    
    
     
     
}
//輸入開頭與結束日期 取出歷史資料
-(NSMutableDictionary *)Get_hisstory_data_startdate:(NSDate *)start_date end_date:(NSDate *)end_date{
    
    NSUInteger flags=NSYearCalendarUnit |NSMonthCalendarUnit |NSDayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit |NSSecondCalendarUnit;  
    
    NSCalendar *calendar  = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSTimeZone *zone  = [NSTimeZone   timeZoneWithName:timezone];
    [calendar  setTimeZone:zone ];    
    
    
    NSDateComponents *comp_start_date =[calendar  components:flags fromDate:start_date];
    NSDateComponents *comp_end_date =[calendar  components:flags fromDate:end_date];    
    
    //NSLog(@"start_date=%@",start_date );
    //NSLog(@"end_date=%@",end_date);
    [calendar release];
    
    
    
    
    NSString *urls_his=[[NSString stringWithFormat:@"http://ichart.yahoo.com/table.csv?s=%@&a=%ld&b=%ld&c=%ld&d=%ld&e=%ld&f=%ld&g=d&ignore=.csv",code,[comp_start_date month]-1,[comp_start_date day],[comp_start_date year],[comp_end_date month]-1,[comp_end_date day],[comp_end_date year]  ] stringByReplacingOccurrencesOfString:@"^" withString:@"%5E"] ;
    
    
    // NSString *urls_his=[NSString stringWithFormat:@"http://ichart.yahoo.com/table.csv?s=2330.tw&a=%ld&b=%ld&c=%ld&d=%ld&e=%ld&f=%ld&g=d&ignore=.csv",1,1,2009,3,28,2012];
    
    
    
    NSLog(@"MultiServer urls=%@",urls_his);
    
    
    //2.轉成 NSURL
    NSURL *url = [NSURL URLWithString:urls_his];   
    
    
    //3.製作request
    NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                    autorelease];
    
    [request setValue:Yahoo_web_User_Agent forHTTPHeaderField:@"User-Agent"];
    
    
    
    //4.下載data
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];    
    //5.data 資料轉成string
    NSString  *download_string_yahoo;
    download_string_yahoo = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];    
   
    //NSLog(@"download_string_yahoo=%@",download_string_yahoo  );
    
    
    NSArray *data_array=[download_string_yahoo  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    
       
    
    BOOL issetHighLow;
    issetHighLow=NO;               
    
    NSMutableArray *outarray_his_data; //歷史資料
    outarray_his_data=[[[NSMutableArray alloc] init] autorelease];
    
    double his_data_high; // 最大值
    double his_data_low;  // 最小值 
    his_data_low=0;
    his_data_high=0;    
    
    NSDate *last_his_date=[NSDate dateWithTimeIntervalSince1970:9999];
    NSNumber *last_his_close=[NSNumber numberWithFloat: 0 ];      
    
    
    //表示至少要有兩行且開頭：Date 可以確保是有效的資料
    if ([data_array count]>=2 && [download_string_yahoo hasPrefix:@"Date"]) {
        
        for (int i=1; i<[data_array count] ;i++ )  {
            NSString *line=[data_array objectAtIndex:i ];
            
            NSArray *line_array;
            line_array = [line componentsSeparatedByString:@","]   ;  
            
            if ([line_array count]==7) {
                //日期                
                
                NSMutableDictionary *dic;
                dic=[[NSMutableDictionary alloc] init];                  
                
                
                NSDate *dates;
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd"];
                [dateFormatter setTimeZone: [NSTimeZone   timeZoneWithName:timezone]];
                dates = [dateFormatter dateFromString:[line_array objectAtIndex:0] ];
                //NSLog(@"dates=%@",[line_array objectAtIndex:0] );
                [dateFormatter release];            
                
                double d_close;
                double d_open;
                double d_high;
                double d_low;
                double d_adj_close;                
                int i_volume;
                d_close=[[line_array objectAtIndex:4]  doubleValue ];                    
                d_open=[[line_array objectAtIndex:1]  doubleValue];
                d_low=[[line_array objectAtIndex:3]  doubleValue ];
                d_high=[[line_array objectAtIndex:2]  doubleValue ];  
               
                d_adj_close=[[line_array objectAtIndex:6]  doubleValue ];                 
                i_volume=[[line_array objectAtIndex:5]  intValue ];                 
                
                if (d_low==0) {
                    d_low=d_close;
                }
                if (d_high==0) {
                    d_high=d_close;
                }
                if (d_open==0) {
                    d_open=d_close;
                }
                
                NSNumber *close=[NSNumber numberWithDouble:d_close];
                NSNumber *open=[NSNumber numberWithDouble:d_open];                               
                NSNumber *high=[NSNumber numberWithDouble:d_high];                
                NSNumber *low=[NSNumber numberWithDouble:d_low];                     
                NSNumber *volume=[NSNumber numberWithInt:i_volume];                    
                NSNumber *adjclose=[NSNumber numberWithDouble:d_adj_close];                
                
                //比較取出歷史最大值與最小值
                {
                    if (issetHighLow==NO) {
                        //第一次設定
                        his_data_low=d_close;
                        his_data_high=d_close;
                        issetHighLow=YES;
                    }
                    
                    if (d_high>his_data_high) {
                        his_data_high=d_high;
                    }
                                        
                    if (d_low<his_data_low  ) {
                        his_data_low=d_low;
                    }  
                    
                    if (i==1) {
                        last_his_date=dates;
                        last_his_close=adjclose; //注意此點
                    }
                   
                }
                
                
                
                
                [dic setObject:dates forKey: HIS_basic_date ];
                [dic setObject:close forKey:HIS_basic_close];
                [dic setObject:open forKey:HIS_basic_open];
                [dic setObject:high forKey:HIS_basic_high];
                [dic setObject:low forKey:HIS_basic_low];
                [dic setObject:volume forKey:HIS_basic_vol];
                [dic setObject:adjclose forKey:HIS_basic_adjclose];                     
                
                
                
                //NSLog(@"line=%@",line);
                
                //限制只有交易量的時間才可以納入 或是指數才可以加入（指數有可能成交量是0）
                if (i_volume>0 || [code hasPrefix:@"^"]) {
                    [outarray_his_data addObject:dic];
                }
                
              
                [dic release];                     
                
                //NSLog(@"%@",dates);
                
            } 
            
        }        
        //反轉
        NSMutableArray * reversed = [[[outarray_his_data reverseObjectEnumerator] allObjects] mutableCopy]; 
        
        //將歷史資料檔案陣列 最大值 最小值 存放在Dictionary，用來傳出去
        NSMutableDictionary *out_dic=[[[NSMutableDictionary alloc] init] autorelease];
        [out_dic setObject:code forKey:DB_object_sqlite_basic_code];
        [out_dic setObject:reversed forKey:@"his_data"];
        [reversed release];
        [out_dic setObject:[NSNumber numberWithDouble: his_data_high] forKey:@"his_data_high"];
             
        [out_dic setObject:[NSNumber numberWithDouble: his_data_low] forKey:@"his_data_low"];      
        [out_dic setObject:last_his_date forKey:@"last_his_date"];
        [out_dic setObject:last_his_close forKey:@"last_his_close"];
        
        return out_dic;        
        
        
    }
    else {
        return nil;
    }
    
} 

//取出最近五日的資料
-(NSMutableArray *)Get_5d_hisstory_data{
   
    NSString *urls_his=[NSString stringWithFormat:@"http://chartapi.finance.yahoo.com/instrument/1.0/%@/chartdata;type=quote;range=5d/csv/",code];
     
    //2.轉成 NSURL
    NSURL *url = [NSURL URLWithString:urls_his];   
    
    
    //3.製作request
    NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                    autorelease];
    
    [request setValue:Yahoo_web_User_Agent forHTTPHeaderField:@"User-Agent"];
     
    //4.下載data
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];    
    //5.data 資料轉成string
    NSString  *download_string_yahoo;
    download_string_yahoo = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];    
    
   // NSLog(@"download_string_yahoo=%@",download_string_yahoo);
    NSArray *data_array=[download_string_yahoo  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];   
   
    [download_string_yahoo release];
    
    if ([data_array count]>1) {
        BOOL begin_read_data;
        begin_read_data=NO;
        
        //開始讀取日內資料
       // BOOL write_open;
       // BOOL write_close;
        int write_day;
        //write_open=NO;
        //write_close=YES;
        write_day=0;
        
        double open;
        double high;
        double low;
        double close;
        double volume;
        open=0;
        high=0;
        //close=0;
        low=0;
        volume=0;
        
        NSMutableArray *RANGE_ARRAY;
        RANGE_ARRAY=[[[NSMutableArray alloc] init] autorelease];
        
        
        
        for (NSString *line in data_array  ) {
            // NSLog(@"%@",line);
            if ([line hasPrefix:@"range:"]) {
                
                NSString *date_timeS_timeE;
                date_timeS_timeE=  [line stringByReplacingOccurrencesOfString:@"range:" withString:@""];
                NSArray *date_timeS_timeE_array;
                date_timeS_timeE_array = [date_timeS_timeE componentsSeparatedByString:@","]   ;              
                if ([ date_timeS_timeE_array count ]==3) {
                    
                    NSMutableDictionary *dd=[[NSMutableDictionary alloc] init];
                    [dd setObject:[date_timeS_timeE_array objectAtIndex:0] forKey:@"day"];
                    [dd setObject:[date_timeS_timeE_array objectAtIndex:1] forKey:@"start"];
                    [dd setObject:[date_timeS_timeE_array objectAtIndex:2] forKey:@"end"];                
                    [RANGE_ARRAY addObject:dd];
                    [dd release];
                }
                
                
            }
            
            
            if (begin_read_data==YES) {
                //Timestamp,close,high,low,open,volume
                
                NSArray *data;
                data = [line componentsSeparatedByString:@","]   ;
                int timestarmp;
                timestarmp=[[data objectAtIndex:0] intValue];
                
                for (NSMutableDictionary *rd in RANGE_ARRAY) {
                    int start;
                    int end;
                    start=[[rd objectForKey:@"start"] intValue];
                    end =[[rd objectForKey:@"end"] intValue];
                    
                    if (start<=timestarmp && timestarmp<=end) {
                        //表示剛好符合再區間內
                        
                        if (write_day!=[[rd objectForKey:@"day"] intValue]) {
                            //NSLog(@"right write_open=%@",[rd objectForKey:@"day"]);
                            close=[[data objectAtIndex:1] doubleValue];
                            high=[[data objectAtIndex:2] doubleValue];
                            low=[[data objectAtIndex:3] doubleValue]; 
                            open=[[data objectAtIndex:4] doubleValue];  
                            volume=[[data objectAtIndex:5] doubleValue]; 
                        }
                        else {
                            //NSLog(@"right =%@",[rd objectForKey:@"day"]);
                            close=[[data objectAtIndex:1] doubleValue];
                            if (high <=[[data objectAtIndex:2] doubleValue]) {
                                high=[[data objectAtIndex:2] doubleValue];
                            }
                            if (low>=[[data objectAtIndex:3] doubleValue]) {
                                low=[[data objectAtIndex:3] doubleValue];
                            }
                            volume=volume+ [[data objectAtIndex:5] doubleValue];
                        }
                        
                        
                        write_day=[[rd objectForKey:@"day"] intValue];                      
                        
                        //將資料存到 rd array
                        NSDate *dates;
                        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
                        [dateFormatter setDateFormat:@"yyyyMMdd"];
                        [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
                        dates = [dateFormatter dateFromString:[rd objectForKey:@"day"] ];
                        [dateFormatter release];                      
                        
                        [rd setObject:dates forKey:HIS_basic_date];                    
                        [rd setObject:[NSNumber numberWithDouble: close] forKey:HIS_basic_close];
                        [rd setObject:[NSNumber numberWithDouble: open] forKey:HIS_basic_open]; 
                        [rd setObject:[NSNumber numberWithDouble: high] forKey:HIS_basic_high]; 
                        [rd setObject:[NSNumber numberWithDouble: low] forKey:HIS_basic_low];                     
                        [rd setObject:[NSNumber numberWithDouble: volume] forKey:HIS_basic_vol];                     
                        [rd setObject:[NSNumber numberWithDouble: close] forKey:HIS_basic_adjclose];                    
                        
                    }
                    
                    
                    
                    
                }
                
                
            }
            
            if ([line hasPrefix:@"volume:"]) {
                begin_read_data=YES;
            }        
            
        }
       
        return RANGE_ARRAY;        
    }
    else {
        return nil;
    }
    
       
   
}

//輸入NSDate 轉出int
-(int)convert_NSDate_to_int:(NSDate *)nsdate{
    NSDateFormatter *dateFormatters = [[[NSDateFormatter alloc] init] autorelease];
    dateFormatters.dateFormat = @"yyyyMMdd";
    
    int  timeStamp_file_last_date = [[dateFormatters stringFromDate:nsdate] intValue];      
    
    return timeStamp_file_last_date;
}


@end
